package top.lshaci.framework.dingtalk.config;

import com.dingtalk.api.DefaultDingTalkClient;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import top.lshaci.framework.dingtalk.properties.DingTalkProperties;
import top.lshaci.framework.dingtalk.service.DingTalkService;
import top.lshaci.framework.dingtalk.service.impl.DefaultDingTalkService;
import top.lshaci.framework.dingtalk.service.impl.SignDingTalkService;

/**
 * DingTalkConfig
 *
 * @author lshaci
 * @since 1.0.8
 */
@Slf4j
@Configuration
@AllArgsConstructor
@EnableConfigurationProperties(DingTalkProperties.class)
@ConditionalOnProperty(prefix = DingTalkProperties.PREFIX, value = "enabled", matchIfMissing = true)
public class DingTalkConfig {

    private final DingTalkProperties properties;

    /**
     * Default ding talk client
     *
     * @return DefaultDingTalkClient
     */
    @Bean
    public DefaultDingTalkClient defaultDingTalkClient() {
        log.debug("Config default ding talk client...");
        return new DefaultDingTalkClient(properties.getServerUrl());
    }

    /**
     * Default ding talk service
     *
     * @return DefaultDingTalkService
     */
    @Bean
    @ConditionalOnMissingBean
    public DingTalkService defaultDingTalkService() {
        log.debug("Config default ding talk service...");
        return new DefaultDingTalkService(defaultDingTalkClient());
    }

    /**
     * 配置加签请求方式
     */
    @Configuration
    @ConditionalOnProperty(prefix = DingTalkProperties.PREFIX, value = "secret")
    class SignDingTalkServiceConfig {

        /**
         * Sign ding talk service
         *
         * @return SignDingTalkService
         * @throws Exception 创建SignDingTalkService失败
         */
        @Bean
        @ConditionalOnMissingBean
        public DingTalkService signDingTalkService() throws Exception {
            log.debug("Config sign ding talk service...");
            return new SignDingTalkService(properties.getServerUrl(), properties.getSecret());
        }

    }
}
